import re

def has_inline_isbn(string):
    """
    Check for an embedded ISBN in the string, either 10 or 13 characters. Used to check if ISBN is in filename
    """
    res = re.compile('(?=.{13})(97\d{11})').findall(string)
    if len(res) and len(res[0]) == 13:
        return res[0]
    res = re.compile('(?=.{10})(\d{9}(?:\d|X))').findall(string)
    if len(res) and len(res[0]) == 10:
        return res[0]
    return None


def extract_isbns(line):
    """
    Look for formatted ISBN 10 or 13 within a line of text. Will return multiple if found
    """
    res = re.compile('ISBN(?:\-13){0,1}[\x20\:]\x20{0,3}(?=.{17})(97[89]\D\d{1,5}\D\d{1,7}\D\d{1,6}\D(?:\d|X))').findall(line)
    if None == res or len(res) == 0 or len(res) == 1 and len(res[0]) == 0:
        res = re.compile('ISBN(?:\-10){0,1}[\x20\:]\x20{0,3}(?=.{13})(\d{1,5}\D\d{1,7}\D\d{1,6}\D(?:\d|X))').findall(line)
        if None == res or len(res) == 0 or len(res) == 1 and len(res[0]) == 0:
            simple = has_inline_isbn(line)
            if simple:
                return [simple]

    return res

def test_isbn_matching():
    examples=['ISBN 1 12345 123 1',
              'ISBN 1-12345-123-1 ignore this',
              'ISBN: 1234567890 ignore this',
              'ISBN 1234567890 ignore this',
              'ISBN-10: 1 12345 123 1 after text',
              'ISBN-10 1 12345 123 3 after text',
              'ISBN-10 1 12345 123 X after text',
              '9991113339',
              '0201379260_xs.jpg',
              'pre-text ISBN-10: 1-12345-123-1',
              'pre-text ISBN:1-12345-123-2',
              'pre-text ISBN-13: 978-0-1234-4123-2',
              'pre-text ISBN-13: 978-0-1234-4123-X',
              'ISBN 978-0-470-02780-8',
              '023113794X',
              'ISBN-10 0-231-13795-X',
              'ISBN: 1 12345 123 1']

    results=[]
    for line in examples:
#        print extract_isbns(line)
        for item in extract_isbns(line):
            item = re.sub(r'\D', '', item)
            print item
            item.strip()
            results.append(item)

    assert results == [ '1123451231',
              '1123451231',
              '1234567890',
              '1234567890',
              '1123451231',
              '1123451233',
              '112345123X',
              '9991113339',
              '0201379260',
              '1123451231',
              '1123451232',
              '9780123441232',
              '978012344123X',
              '9780470027808',
              '023113794X',
              '023113795X',
              '1123451231']

if __name__ == '__main__':
    test_isbn_matching()
